/**
 * 
 */
package agents.communication;

import es.ucm.fdi.agents.yellowPages.YellowPages;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.TickerBehaviour;
import jade.lang.acl.ACLMessage;

import log.ContadorEventos;
import org.apache.log4j.Logger;

import agents.messages.MessageConstants;
import log.Action;

/**
 * @author Elena
 *
 */
public class Wait4AllPaths extends TickerBehaviour{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private boolean done = false;
	private int leaders = 0;
	private int received = 0;
	private AID[] listaAgentesEstudiantes;
	YellowPages paginasAmarillas;
	
	static Logger logger = Logger.getLogger(CommunicationAgent.class);
	
	public Wait4AllPaths(Agent a, long period) {
		super(a, period);
		paginasAmarillas = new YellowPages();
		listaAgentesEstudiantes = paginasAmarillas.buscarServicio(MessageConstants.SERV_GENERACION_COORDENADAS, myAgent);
		this.leaders = listaAgentesEstudiantes.length;
	}
	@Override
	protected void onTick() {
		
		ACLMessage mensajeEntrante = myAgent.receive();
		
		if(mensajeEntrante != null){
			logger.info(ContadorEventos.addEvent("STATIC", Action.RECIBIR_MSJ, mensajeEntrante.getContent()));
			if (mensajeEntrante.getContent().contains("encontrado")){
				received++;
				if (received==leaders){
					CommunicationAgentBehavior cab = new CommunicationAgentBehavior(myAgent,50);
					genera();
					myAgent.addBehaviour(cab);
					this.stop();
				}
			}
		}
		
	}
	
	private void genera(){
		ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
		for (int i=0;i<listaAgentesEstudiantes.length;i++)
			msg.addReceiver(new AID(listaAgentesEstudiantes[i].getLocalName(),AID.ISLOCALNAME));
		msg.setContent(MessageConstants.MSJ_GENERA_COORDENADAS);
		myAgent.send(msg);
		logger.info(ContadorEventos.addEvent("STATIC",Action.ENVIAR_MSJ,"Primer genera"));
	}
	

	public int onEnd() { 
		logger.info(ContadorEventos.addEvent("STATIC", Action.TERMINAR, ""));
		return 1;
	}

}
